package cn.wsxiot.display.exception;

import cn.wsxiot.display.domain.dto.Result;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
public class MyExceptionHandler {



    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler() throws Exception {
        return new ModelAndView("error");
    }


    /**
     * throw  new MyException("测试异常");
     * @param req
     * @param resp
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(value = MyException.class)
    @ResponseBody
    public Result<String> jsonErrorHandler(HttpServletRequest req, HttpServletResponse resp, MyException e) throws Exception {
        Result<String> ret = new Result<>();
        ret.setMessage(e.getMessage());
        ret.setCode(Result.ERROR);
        ret.setData("Some Data");
        ret.setUrl(req.getRequestURL().toString());
        return ret;
    }



    @ModelAttribute
    public Model newUser(Model model) {
//        System.out.println("============应用到所有@RequestMapping注解方法，在其执行之前把返回值放入Model");
        model.addAttribute("user","test");
        return model;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
//        System.out.println("============应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器");
    }

}
